/*
 * @Date: 2021-09-09 17:27:12
 * @Author: Acckno1
 * @LastEditTime: 2021-09-09 19:32:19
 * @Description: 
 */
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <utility>
using namespace std;

#define mm(a, n) memset(a, n, sizeof a)
#define mk(a, b) make_pair(a, b)

const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef pair<LL, LL> PLL;
typedef pair<int, LL> PIL;

inline void quickread() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
}

const int N = 310;
int g[N][N];
int n, m;
vector<int> boys, girls;
int idx;
unordered_map<string, int> mp; // k:id of string, v:index
unordered_map<int, string> nums; // k:index, v:id of string


inline void solution() {
    cin >> n >> m;
    for (int i = 0; i < m; i ++ ) {
        string a, b;
        cin >> a >> b;
        string x = a, y = b;
        if (x[0] == '-') x = x.substr(1);
        if (y[0] == '-') y = y.substr(1);
        if (mp.count(x) == 0) mp[x] = ++ idx, nums[idx] = x;
        if (mp.count(y) == 0) mp[y] = ++ idx, nums[idx] = y;

        int px = mp[x], py = mp[y];
        g[px][py] = g[py][px] = true;

        if (a[0] == '-') girls.push_back(px);
        else boys.push_back(px);
        if (b[0] == '-') girls.push_back(py);
        else boys.push_back(py);
    }

    sort(boys.begin(), boys.end());
    boys.erase(unique(boys.begin(), boys.end()), boys.end());
    sort(girls.begin(), girls.end());
    girls.erase(unique(girls.begin(), girls.end()), girls.end());
    
    int k;
    cin >> k;
    while (k -- ) {
        vector<pair<string, string>> res;
        string x, y;
        cin >> x >> y;

        vector<int> p = boys, q = boys;
        if (x[0] == '-') p = girls, x = x.substr(1);
        if (y[0] == '-') q = girls, y = y.substr(1);

        int a = mp[x], b = mp[y];
        for (int c : p) 
            for (int d : q) 
                if (c != a && c != b && d != a && d != b && g[a][c] && g[c][d] && g[d][b])
                    res.push_back(mk(nums[c], nums[d]));
                    
        sort(res.begin(), res.end());
        cout << res.size() << endl;
        for (auto & r : res) 
            cout << r.first << " " << r.second << endl;
    }
}

int main() {
    freopen("input.txt", "r", stdin);
    quickread();
    solution();
    return 0;
}